class DiscussionsController < ApplicationController
  before_filter :login_required, :except => [ :show, :index ]
  before_filter :find_user, :find_discipline, :except => [ :index ]

  def index
    permission_denied
  end

  def show
    @discussion = Discussion.find(params[:id])
  end

  def new
    @discussion = Discussion.new
  end

  def edit
    @discussion = Discussion.find_by_id_and_user_id(params[:id], current_user.id)
  end

  def create
    @discussion = Discussion.new(params[:discussion])
    @discussion.user = current_user
    @discussion.discipline = @discipline
    respond_to do |format|
      if @discussion.save
        flash[:notice] = "Discussion was successfully started."
        format.html { redirect_to discipline_discussion_path(@discipline, @discussion)}
      else
        format.html { render :action => "new" }
      end
    end
  end

  def update
    @discussion = Discussion.find_by_id_and_user_id(params[:id], current_user.id)
    respond_to do |format|
      if @discussion.update_attributes(params[:discussion])
        flash[:notice] = "Discussion was successfully updated."
        format.html { redirect_to discipline_discussion_path(@discipline, @discussion) }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  def destroy
    @discussion = Discussion.find(params[:id])
    @discussion.destroy
    flash[:notice] = "Discussion was sucessfully deleted."
    respond_to do |format|
      format.html { redirect_to discipline_url(@discipline) }
    end
  end

  protected

  def authorized?
    logged_in? and current_user.admin? or (params[:id].nil? || Discussion.find(params[:id]).user == current_user) or %w(index new create show).include?(action_name)
  end

end
